package com.plian.system.service.mt.assigmat;

import com.plian.Tools.TokenUtil;
import com.plian.Tools.Tools;
import com.plian.Tools.UuidUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.dao.mt.assigmat.AssigMatDao;
import com.plian.system.dao.mt.todo.TodoDao;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.page.Page;
import com.plian.system.service.sys.code.impl.FormCodeServiceImpl;
import com.plian.system.service.sys.file.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class AssigMatService {
    @Autowired
    AssigMatDao assigMatDao;
    @Autowired
    TodoDao todoDao;
    @Autowired
    FileService fileService;
    @Autowired
    FormCodeServiceImpl formCodeService;
    public ListResult list(PageData pd){
        ListResult listResult;
        try {
            pd.put("userId",TokenUtil.getTokenUserId());
            Page page =  new Page(true, pd);
            listResult = new ListResult(CommonCode.SUCCESS);
            List<PageData> list =  assigMatDao.list(page);
            listResult.setTotal(page.getTotal());
            listResult.setList(list);
        }catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            listResult = new ListResult(CommonCode.ERROR);
        }
        return listResult;
    }

    /**
     * 保存
     * @param pd
     * @return
     */
    @Transactional(rollbackFor=RuntimeException.class)
    public ObjResult save(PageData pd) {
        ObjResult objResult;
        try {
            String id = UuidUtil.get32UUID();
            pd.put("id", id);
            pd.put("status", "0");
            pd.put("formType",String.valueOf(FormTypeConstant.MT_ASSIGMAT));
            pd.put("code", formCodeService.getCode(FormTypeConstant.MT_ASSIGMAT));
            pd.put("userId",TokenUtil.getTokenUserId());
            pd.remove("assigmatTime");
            pd.put("createTime",new Date());
            pd.put("updataTime", new Date());
            assigMatDao.save(pd);
            objResult= new ObjResult(CommonCode.SUCCESS);
            fileService.saveAll(id,(List<HashMap>) pd.get("list_doc"));
        } catch (Exception e) {
            objResult=  new ObjResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return objResult;
    }
    /**
     * 修改
     * @param pd
     * @return
     */
    @Transactional(rollbackFor=RuntimeException.class)
    public ObjResult edit(PageData pd) {
        ObjResult objResult;
        try {
            String id = pd.getString("id");
            pd.put("updataTime", new Date());
            assigMatDao.edit(pd);
            fileService.edit(id,(List<HashMap>) pd.get("list_doc"));
            objResult= new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            objResult=  new ObjResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }

        return objResult;
    }

    /**
     *
     * @param pageData
     * @return
     */
    public ObjResult del_ids(PageData pageData) {
        ObjResult objResult;
        try {
            if(!Tools.isEmpty(pageData.getString("ids"))){
                String string  = pageData.getString("ids");
                String[] arr = string.replace("[","").replace("]","").split(",");
                for(String a :arr){
                    pageData.put("ids",a.trim());
                    assigMatDao.delete(pageData);
                }
                objResult= new ObjResult(CommonCode.SUCCESS);
            }else {
                objResult= new ObjResult(CommonCode.FAIL);
            }
        } catch (Exception e) {
            objResult=  new ObjResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return objResult;
    }

    /**
     * 根据id查询
     * @param p
     * @throws Exception
     */
    public ObjResult findbyid(PageData p) {
        try {
            PageData pageData=assigMatDao.findById(p);
            ObjResult objResult=new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(pageData);
            return objResult;
        }catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }

    }

    /**
     * 下发
     * @param p
     * @return
     */
    public ObjResult lowerHair(PageData p) {
        ObjResult objResult;
        try {
            String DATA_IDS = p.getString("ids");
            if(null != DATA_IDS && !"".equals(DATA_IDS)) {
                String ArrayDATA_IDS[] = DATA_IDS.replace("[","").replace("]","").split(",");
                //更改对应id的状态
                for (int i = 0; i < ArrayDATA_IDS.length; i++) {
                    PageData pdd = new PageData();
                    pdd.put("id", ArrayDATA_IDS[i]);
                    pdd = assigMatDao.findById(pdd);
                    if(null!= pdd.getString("todoOrg") && !"".equals(pdd.getString("todoOrg"))){
                        String orgCode = pdd.getString("todoOrg");
                        String CodeS[] = orgCode.split(",");
                        for (int j = 0; j < CodeS.length; j++) {
                            PageData pageData = new PageData();
                            pageData.put("todoId", UuidUtil.get32UUID());
                            pageData.put("assigmatCode", pdd.getString("code"));
                            pageData.put("todoStatus", "0");
                            pageData.put("assigmatTime", new Date());
                            pageData.put("updataTime", new Date());
                            pageData.put("createTime", new Date());
                            pageData.put("assigmatDepartmentd", pdd.getString("assigmatDepartmentd"));
                            pageData.put("assigmatName", pdd.getString("assigmatName"));
                            pageData.put("assignReamark", pdd.getString("assignReamark"));
                            pageData.put("assignDemand", pdd.getString("assignDemand"));
                            pageData.put("feedbackTime", pdd.getString("feedbackTime"));
                            pageData.put("includedCheck", pdd.getString("includedCheck"));
                            pageData.put("assigmatId", ArrayDATA_IDS[i]);
                            pageData.put("ptodoId","0");
                            pageData.put("todoParnetId", pdd.getString("id"));
                            pageData.put("todoOrg", CodeS[j]);
                            pageData.put("assigmatTime",new Date());
                            pageData.put("sendName", pdd.getString("userId"));
                            todoDao.save(pageData);
                        }
                    }
                    if(null!= pdd.getString("todoUser") && !"".equals(pdd.getString("todoUser"))){
                        String User = pdd.getString("todoUser");
                        String user[] = User.split(",");
                        for (int j = 0; j < user.length; j++) {
                            PageData pageData = new PageData();
                            pageData.put("todoId", UuidUtil.get32UUID());
                            pageData.put("assigmatCode", pdd.getString("code"));
                            pageData.put("todoStatus", "0");
                            pageData.put("assigmatTime", new Date());
                            pageData.put("updataTime", new Date());
                            pageData.put("createTime", new Date());
                            pageData.put("assigmatDepartmentd", pdd.getString("assigmatDepartmentd"));
                            pageData.put("assigmatName", pdd.getString("assigmatName"));
                            pageData.put("assignReamark", pdd.getString("assignReamark"));
                            pageData.put("assignDemand", pdd.getString("assignDemand"));
                            pageData.put("feedbackTime", pdd.getString("feedbackTime"));
                            pageData.put("includedCheck", pdd.getString("includedCheck"));
                            pageData.put("assigmatId", ArrayDATA_IDS[i]);
                            pageData.put("todoUser", user[j]);
                            pageData.put("assigmatTime",new Date());
                            pageData.put("ptodoId","0");
                            pageData.put("todoParnetId", pdd.getString("todoId"));
                            pageData.put("sendName", pdd.getString("userId"));
                            todoDao.save(pageData);
                        }
                    }
                    pdd.put("status", "6");
//                    pdd.put("updataTime", new Date());
                    pdd.put("assigmatTime", new Date());
                    assigMatDao.edit(pdd);
                }
            }
            return new ObjResult(CommonCode.SUCCESS);
        }catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }
}
